package org.algorithm.二师兄.数组.二月;

/***
 * @author 二师兄
 * @date 2022-03-02 星期三 19:22
 *
 *  给定一个数组， 求数组中和为给定target的最短子数组
 *
 * 输入：target = 7, nums = [2,3,1,2,4,3]
 * 输出：2
 * 解释：子数组 [4,3] 是该条件下的长度最小的子数组。
 *
 *  uri: https://leetcode-cn.com/problems/2VG8Kg/
 */
public class 最短子数组 {

    public static void main(String[] args) {
        int[] nums = {2,3,1,2,4,3};
        System.out.println(minSubArrayLen(7, nums));
    }

    public static int minSubArrayLen(int target, int[] nums) {
        if (nums == null || nums.length < 2) return nums[0];
        int n = nums.length;
        int ans = Integer.MAX_VALUE;
        int start = 0, end = 0;
        int sum = 0;
        while (end < n) {
            sum += nums[end];
            while (sum >= target) {
                ans = Math.min(ans, end - start + 1);
                sum -= nums[start];
                start++;
            }
            end++;
        }
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}
